package com.adou.multi.multi_tenancy.aspect;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.hibernate.Filter;
import org.hibernate.Session;

import com.adou.multi.multi_tenancy.util.TeanantContext;

@Aspect
public class TenantFilterAspect {
	@Pointcut("execute (* org.hibernate.internal.SessionFactoryImpl.SessionBuilderImpl.openSession(..))")
	public void openSession(){
		
	}
	
	@AfterReturning(pointcut="openSession()", returning="session")
	public void afterOpenSession(Object session){
		if(session != null && Session.class.isInstance(session)){
			final String tenantId = TeanantContext.getTenantId();
			if(tenantId != null){
				Filter filter = ((Session)session).enableFilter("tenantFiletr");
				filter.setParameter("tenantId", tenantId);
			}
		}
	}
}
